import { get, post, del } from '@/utils/request';

export interface FileRecord {
  id: string;
  tenantId?: string;
  userId: string;
  originalName: string;
  fileName: string;
  mimeType: string;
  size: number;
  path: string;
  url?: string;
  category: 'document' | 'image' | 'video' | 'audio' | 'other';
  bucket?: string;
  storageType: 'local' | 'oss' | 's3' | 'minio';
  description?: string;
  metadata?: any;
  createdAt: string;
  updatedAt: string;
  user?: {
    id: string;
    firstName?: string;
    lastName?: string;
    email: string;
  };
}

export interface FileListParams {
  page?: number;
  pageSize?: number;
  category?: 'document' | 'image' | 'video' | 'audio' | 'other';
  originalName?: string;
}

/**
 * 上传单个文件
 */
export const uploadFile = (file: File) => {
  const formData = new FormData();
  formData.append('file', file);
  return post<FileRecord>('/files/upload', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  } as any);
};

/**
 * 批量上传文件
 */
export const uploadFiles = (files: File[]) => {
  const formData = new FormData();
  files.forEach((file) => {
    formData.append('files', file);
  });
  return post<FileRecord[]>('/files/upload/multiple', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  } as any);
};

/**
 * 获取文件列表
 */
export const getFiles = (params: FileListParams) => {
  return get<any>('/files', params);
};

/**
 * 获取文件详情
 */
export const getFileById = (id: string) => {
  return get<FileRecord>(`/files/${id}`);
};

/**
 * 下载文件
 */
export const downloadFile = (id: string, filename: string) => {
  const token = localStorage.getItem('access_token');
  const url = `${import.meta.env.VITE_API_BASE_URL || 'http://localhost:4321/api'}/files/${id}/download`;
  
  // 创建隐藏的a标签进行下载
  const link = document.createElement('a');
  link.href = `${url}?token=${token}`;
  link.download = filename;
  link.style.display = 'none';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

/**
 * 删除文件
 */
export const deleteFile = (id: string) => {
  return del(`/files/${id}`);
};

/**
 * 批量删除文件
 */
export const batchDeleteFiles = (ids: string[]) => {
  return post('/files/batch-delete', { ids });
};

